require('./db/index.js')//此处有改动
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
let cors = require('cors');

var indexRouter = require('./routes/index');
var jzlRouter = require('./routes/jzl');
var llxRouter = require('./routes/llx');
var jjxRouter = require('./routes/jjx');
var zbsRouter = require('./routes/zbs');
var jbhRouter = require('./routes/jbh');
var lyxRouter = require('./routes/lyx');
var usersRouter = require('./routes/users');


var app = express();

// 优化CORS配置，明确允许的源和方法
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 只在开发环境使用详细日志
app.use(logger(process.env.NODE_ENV === 'production' ? 'combined' : 'dev'));

app.use('/upload', express.static(path.join(__dirname, 'upload')));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 添加CORS支持 - 移到路由之前
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

// 虚拟恋人图片静态文件服务
app.use('/outfit_images', express.static(path.join(__dirname, 'py_service/outfit_images')));

// 添加Python服务代理路由 - 使用更具体的路径
app.use('/api/py', require('./routes/jzl'));


// 优化静态资源
app.use(express.static(path.join(__dirname, 'public'), {
  maxAge: '1d', // 静态资源缓存1天
  etag: true,
  lastModified: true
}));

// 路由
app.use('/', indexRouter);
app.use('/jzl', jzlRouter);
app.use('/llx', llxRouter);
app.use('/zbs', zbsRouter);
app.use('/jjx', jjxRouter);
app.use('/jbh', jbhRouter);
app.use('/lyx', lyxRouter);
app.use('/users', usersRouter);

// 静态文件中间件
app.use(express.static(path.join(__dirname, '../one/dist')));

// 所有非API请求路由到前端
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../one/dist/index.html'));
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
